import {Component} from '@angular/core';
import {AlertController, Events, IonicPage, LoadingController, NavController, NavParams} from 'ionic-angular';
import {GraphicUnlockPage} from "../../graphic-unlock/graphic-unlock";
import {UnlockService} from '../../../services/native/authentication/authentication.service';
import {AlertButton, AlertInputOptions} from "ionic-angular/components/alert/alert-options";
import {ToastService} from "../../../services/common/toast.service";

@IonicPage()
@Component({
    selector: 'page-graphic-unlock-setting',
    templateUrl: 'graphic-unlock-setting.html',
})
export class GraphicUnlockSettingPage {
    /*默认未使用手势密码*/
    public isUseGraphicLock: boolean;

    private hasStoredGraph: boolean;
    private disabledNextEvent: boolean;

    constructor(public navCtrl: NavController, public navParams: NavParams, private events: Events,
                private toastService: ToastService,
                public loadCtr: LoadingController,
                private alertCtrl: AlertController, private unlockService: UnlockService) {

    }

    ionViewDidLoad() {
        this.navParams.get('fromPage');
        this.getGraphicSetting();
    }

    ionViewDidEnter() {
        this.disabledNextEvent = false;
        this.getGraphicSetting();
    }

    getGraphicSetting() {
        this.unlockService.isGraphicEnabled().then(enabled => {
            this.isUseGraphicLock = enabled;
        });
        this.unlockService.hasStoredGraphic().then(stored => {
            this.hasStoredGraph = stored;
        });
    }

    //修改手势
    modifyGraphicLock() {
        //验证用户密码
        this.onSwitchChange('modify');
    }

    setGraphicLockChange() {
        if (this.isUseGraphicLock) {
            //禁用 需要验证手势密码
            this.onSwitchChange('close');
        } else {
            //表示之前是开启手势，现在关闭手势
            //如果已开启指纹 则提示指纹将关闭 验证用户名
            this.unlockService.isFingerprintEnabled().then(enabled => {
                if (enabled) {
                    this.showAlert('启用手势密码将会关闭指纹解锁',()=>{
                        this.onSwitchChange('');
                    });
                }
                else {
                    //未开启指纹验证，直接
                    this.navCtrl.push('GraphicUnlockPage', {
                        lockType: 1
                    })
                }
            })
        }
    }

    showAlert(msg, callback?) {
        this.alertCtrl.create({
            message: msg,
            cssClass: 'custom-alert',
            buttons: [{
                role: 'cancel',
                text: '确定',
                handler: () => {
                    callback && callback();
                }
            }]
        }).present();
    }

    onSwitchChange(flag) {
        const inputOptions: AlertInputOptions = {
            name: 'password',
            placeholder: '请输入您的登录密码',
            type: 'password'
        };
        const cancelButton: AlertButton = {
            text: '取消',
            role: 'cancel',
            handler: () => {
            }
        };

        const okButton: AlertButton = {
            text: '确定',
            handler: data => {
                if (!data.password) {
                    this.showAlert('请输入登录密码');
                    return;
                }
                let loading = this.loadCtr.create({
                    spinner: 'circles',
                    content: "验证中",
                });

                loading.present();
                this.unlockService.validatePassword(data.password).then(result => {
                    loading.dismiss();
                    if (result === 'offLine') {
                        //断网
                        this.showAlert('当前网络环境异常，请稍后重试');

                        this.events.publish('checkNet');
                        return;
                    }
                    if (result === 'fail') {
                        //密码验证失败
                        this.unlockService.passwordRemainAttemps().then(remain => {
                            if (remain > 0) {
                                this.showAlert(`验证失败,还可以输入${remain}次`);
                            }
                            else {
                                this.showAlert(`验证错误次数已达上限，请重新登录`);
                            }
                        });
                        return;
                    }

                    if (result === 'netWork') {
                        this.showAlert(`当前网络环境异常，请稍后重试`);
                        return;
                    }
                    //验证密码通过后，关闭指纹登录
                    this.unlockService.switchFingerprintLogin(false);

                    if (flag === 'close') {
                        //关闭手势 改变状态
                        this.isUseGraphicLock = false;
                        this.unlockService.switchGraphicLogin(false);
                    } else {
                        //之前开启了指纹 密码验证通过 直接重置手势密码
                        this.navCtrl.push('GraphicUnlockPage', {
                            lockType: 1
                        })
                    }
                }, () => {
                    loading.dismiss();
                })

            }
        };

        // 关闭指纹时验证
        this.alertCtrl.create({
            message: '身份验证',
            cssClass: "assist-login-alert-message",
            inputs: [inputOptions],
            buttons: [cancelButton, okButton]
        }).present();
    }
}

